<?php

namespace app\model\order;

use app\base\BaseModel;
use app\factory\logistics\Logistics;
use app\factory\wxPay\WxOut;
use app\libs\Util;
use app\model\activity\ActivityGoodsModel;
use app\model\agency\AgencyGoodsModel;
use app\model\goods\GoodsBuyLogModel;
use app\model\goods\GoodsModel;
use app\model\system\SysConfigModel;
use app\model\user\UserBeanLogModel;
use app\model\user\UserCartModel;
use app\model\user\UserCouponModel;
use app\model\user\UserModel;
use think\Exception;
use think\facade\Cache;
use think\facade\Config;
use think\facade\Db;
use think\model\concern\SoftDelete;

/**
 * 模型-order
 * Class OrderModel
 * @package app\model
 */
class OrderModel extends BaseModel
{
    use SoftDelete;

    protected $name = 'order';

    /**
     * 店铺id 查询范围
     * @param $query
     * @param $id
     */
    public function scopeStoreId($query, $id)
    {
        if (!empty($id)) {
            $query->alias("a");
            $query->where('a.store_id', $id);
        }
    }

    /**
     * 范围查询-create_date_day
     * @param $query
     * @param array $time
     */
    public function scopeTime($query, $time = [])
    {
        if (!empty($time)) {
            $query->where('a.create_date_day', 'between', $time);
        }
    }

    /**
     * 范围查询-order_out_handle_status
     * @param $query
     * @param string $op
     * @param $status
     */
    public function scopeOrderOutHandleStatus($query, $status)
    {
        $op = "=";
        if (intval($status) == 0) {
            $op = ">";
        }
        $query->where('a.out_handle_status', $op, $status);
    }

    /**
     * 范围查询-order_status
     * @param $query
     * @param $status
     */
    public function scopeStatus($query, $status)
    {
        # 不能判断0和""
        if (!empty($status)) {
            if ($status == 6) {
                $status = 0;
            }
            $query->where('a.order_status', '=', $status);
        }
    }

    /**
     * 范围查询-order_status
     * @param $query
     * @param $status
     */
    public function scopeAgencyId($query, $agency_id)
    {
        if (!empty($agency_id)) {
            $query->where('a.agency_id', '=', $agency_id);
        }
    }

    /**
     * 范围查询-order_number
     * @param $query
     * @param $keyword
     */
    public function scopeKeyword($query, $keyword)
    {
        if (!empty($keyword)) {
            $query->whereLike('a.order_sn', '%' . trim($keyword) . '%', 'OR');
            $query->whereLike('a.pay_sn', '%' . trim($keyword) . '%', 'OR');
            $query->whereLike('a.take_name', '%' . trim($keyword) . '%', 'OR');
            $query->whereLike('a.take_phone', '%' . trim($keyword) . '%', 'OR');
        }
    }

    /**
     * 范围查询-order_number
     * @param $query
     * @param $keyword
     */
    public function scopeAgencyKeyword($query, $keyword)
    {
        if (!empty($keyword)) {
            $query->whereLike('a.take_name', '%' . trim($keyword) . '%', 'OR');
            $query->whereLike('a.take_phone', '%' . trim($keyword) . '%', 'OR');
        }
    }

    /**
     * 范围查询-create_time
     * @param $query
     * @param $time
     */
    public function scopeCreateTime($query, $time = [])
    {
        if (!empty($time)) {
            $query->where('a.create_time', 'between', $time);
        }
    }

    /**
     * 范围查询-goods_type  是否拼团
     * @param $query
     * @param string $pt
     */
    public function scopeGoodsType($query, $pt = 'all')
    {
        if ($pt != 'all') {
            if ($pt == 'yes') {
                $query->where('goods_type', 1);
            } else {
                $query->where('goods_type', 0);
            }
        }
    }

    /**
     * 格式化数据
     * @param $item
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function formatx(&$item)
    {
        $order_detail = Db::name('order_item')->alias('a')->join('t_goods_common b', 'a.attribute_ids=b.attribute_ids')->where("a.order_id", $item['id'])->field('a.id,a.goods_id,a.goods_number,a.platform_price,a.cost_price,a.agency_price,a.agency_money,a.send_number,a.order_status,b.goods_title,b.attribute_names')->select();
        $total_profit = 0;
        $total_agency_money = 0;
        if ($item['order_status'] >= 2) {
            $total_profit = $item['actual_price'] - $item['cost_price'] - $item['freight_price'];
        }
        if (intval($item['agency_id']) >= 1) {
            $agency_ratio = $item['agency_ratio'];
            $total_agency_money = $total_profit * $agency_ratio;
        }
        $total_platform_money = $total_profit - $total_agency_money;
        $item['order_detail'] = $order_detail;
        $item['total_profit'] = round($total_profit, 2);
        $item['total_agency_money'] = round($total_agency_money, 2);
        $item['total_platform_money'] = round($total_platform_money, 2);
        $item['total_cost_price'] = round($item['cost_price'] + $item['freight_price'], 2);
        $order_item_logistics_model = new OrderItemLogisticsModel();
        $item['logistics_numbers'] = $order_item_logistics_model->getChildInfo($item['id']);

        return $item;
    }

    /**
     * 获取分页列表
     * @param $status
     * @param $keyword
     * @param $current_page
     * @param $list_rows
     * @param array $time
     * @param string $pt
     * @param string $agency_id
     * @param string $order
     * @param int $store_id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getPageData($status, $keyword, $current_page, $list_rows, $time = [], $pt = 'all', $agency_id = '', $order = 'a.create_time desc', $store_id = 0)
    {
        if (intval($status) == 6) {
            $model = $this->withTrashed();
        } else {
            $model = $this;
        }
        $dataList = $model
            ->alias("a")
            ->join("t_user b", "a.user_id=b.id")
            ->leftJoin("t_agency c", "a.agency_id=c.id")
            ->field('a.*,b.head_img,b.nick_name,c.agency_title')
            ->status($status)
            ->agencyId($agency_id)
            ->storeId($store_id)
            ->keyword($keyword)
            ->createTime($time)
            ->goodsType($pt)
            ->order($order)
            ->paginate(['page' => $current_page, 'list_rows' => $list_rows], false)
            ->each(function ($item, $value) {
                # 订单详情
                $this->formatx($item);
                return $item;
            });
        $current = $dataList->currentPage();
        $total = $dataList->total();
        $limit = $dataList->listRows();
        $items = $dataList->items();
        $ret = ['total' => $total, 'current' => $current, 'limit' => $limit, 'dataList' => $items];
        return $ret;
    }

    /**
     * 待发货订单列表
     * @param $keyword
     * @param $current_page
     * @param $list_rows
     * @param string $field
     * @param array $time
     * @param string $pt
     * @param int $store_id
     * @return array
     */
    public function getSendPageData($keyword, $current_page, $list_rows, $field = '*', $time = [], $pt = 'all', $store_id = 0)
    {
        $dataList = $this
            ->alias("a")
            ->storeId($store_id)
            ->leftJoin("t_user b", "a.user_id=b.id")
            ->leftJoin("t_order_item c", "a.id=c.order_id")
            ->where('c.goods_source', 'system')
            ->where('c.goods_type', '<>', 1)
            ->field($field)
            ->status(2)
            ->keyword($keyword)
            ->createTime($time)
            ->goodsType($pt)
            ->order('a.create_time', 'desc')
            ->group('c.order_id')
            ->paginate(['page' => $current_page, 'list_rows' => $list_rows], false);
        $current = $dataList->currentPage();
        $total = $dataList->total();
        $limit = $dataList->listRows();
        $items = $dataList->items();
        $ret = ['total' => $total, 'current' => $current, 'limit' => $limit, 'dataList' => $items];
        return $ret;
    }

    /**
     * 获取退款列表
     * @param $status
     * @param $outStatus
     * @param $keyword
     * @param $current_page
     * @param $list_rows
     * @param $field
     * @param $store_id
     * @return array
     */
    public function getOutPageData($status, $outStatus, $keyword, $current_page, $list_rows, $field = "a.*,b.head_img,b.nick_name,c.agency_title", $store_id = 0)
    {
        $dataList = $this
            ->alias("a")
            ->leftJoin("t_user b", "a.user_id=b.id")
            ->leftJoin("t_agency c", "a.agency_id=c.id")
            ->storeId($store_id)
            ->field($field)
            ->orderOutHandleStatus($outStatus)
            ->status($status)
            ->keyword($keyword)
            ->order('id desc')
            ->paginate(['page' => $current_page, 'list_rows' => $list_rows], false)
            ->each(function ($item, $value) {
                # 订单详情
                $this->formatx($item);
                $item['out_status'] = OrderItemOutModel::getOutStatus($item['id']);
                $item['item_order_total'] = OrderItemModel::getRefundMoney($item['id']);
                $item['item_order_cost_total'] = OrderItemModel::getRefundCostMoney($item['id']);
                return $item;
            });;
        $items = $dataList->items();
        $current = $dataList->currentPage();
        $total = $dataList->total();
        $limit = $dataList->listRows();
        $ret = ['total' => $total, 'current' => $current, 'limit' => $limit, 'dataList' => $items];
        return $ret;
    }

    /**
     * 获取（BD）推广员退款订单
     * @param string $user_id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getOutOrderMarket($user_id = '')
    {
        $user_ids = UserModel::getMarketUserIds($user_id);
        $dataList = $this
            ->where('out_type', '>', 0)
            ->where('out_handle_status', 1)
            ->whereIn('user_id', $user_ids)
            ->order('a.create_time desc')
            ->each(function ($item, $value) {
                # 订单详情
                $this->formatx($item);
                return $item;
            });
        if (empty($dataList)) {
            return [];
        }
        return $dataList;
    }

    /**
     * 获取（BD）推广员退款订单
     * @param string $user_id
     * @param int $type 1当日订单 2全部订单
     * @param string $time_str 时间2022-06-22
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getListOrderMarket($user_id = '', $type = 1, $time_str)
    {
        $user_ids = UserModel::getMarketUserIds($user_id);
        if ($type == 1) {
            $time = [strtotime(date("Y-m-d")), strtotime(date("Y-m-d")) + (3600 * 24)];
        } else {
            $time = [strtotime($time_str) - (3600 * 24), strtotime($time_str)];
        }
        $dataList = $this
            ->where('out_type', '>', 0)
            ->where('out_handle_status', 1)
            ->whereIn('user_id', $user_ids)
            ->order('a.create_time desc')
            ->createTime($time)
            ->each(function ($item, $value) {
                # 订单详情
                $this->formatx($item);
                return $item;
            });
        if (empty($dataList)) {
            return [];
        }
        return $dataList;
    }


    /**
     * 添加普通订单
     * @param array $goods_data
     * @param $user_data
     * @param int $order_total
     * @param float $cost_price 成本价
     * @param int $channel
     * @param string $keyword 订单关键词
     * @param int $goods_freight 商品运费
     * @param int $store_id 店铺id
     * @param int $goods_type 0非拼团商品 1拼团中 2趣豆商城 3趣豆大礼包
     * @return array
     * @throws \Exception
     */
    public function addOrder($goods_data, $user_data, $order_total = 0, $cost_price = 0.00, $channel = 0, $keyword = "", $goods_freight = 0, $store_id = 0, $goods_type = 0)
    {
        $order_sn = date("YmdHis") . $user_data['user_id'] . mt_rand(1000, 9999);
        $agency_id = $user_data['agency_id'];
        $top_user_id = $user_data['top_user_id'];
        $top_top_user_id = $user_data['top_top_user_id'];
        $order_lng = $user_data['order_lng'];
        $order_lat = $user_data['order_lat'];
        $user_id = $user_data['user_id'];
        $order_keyword = $user_data['take_name'] . "|" . $keyword;
        $in_order = [
            'order_sn' => $order_sn,
            'user_id' => $user_id,
            'store_id' => $store_id,
            'agency_id' => $user_data['agency_id'],
            'order_total' => $order_total,
            'take_address' => $user_data['take_address'],
            'take_name' => $user_data['take_name'],
            'take_phone' => $user_data['take_phone'],
            'take_mode' => $user_data['take_mode'],
            'take_time' => $user_data['take_time'],
            'buy_msg' => $user_data['buy_msg'],
            'discounts' => $user_data['discounts'],
            'coupon_id' => $user_data['coupon_id'],
            'freight_price' => $goods_freight,
            'goods_type' => $goods_type,
            'cost_price' => $cost_price,
            'order_lng' => $order_lng,
            'order_lat' => $order_lat,
            'channel_id' => $channel,
            'order_keyword' => $order_keyword,
            'update_time' => time(),
            'create_time' => time(),
            'create_date_day' => date("Y-m-d"),
            'create_date' => date("Y-m-d H:i:s"),
        ];
        $this->startTrans();
        $ret = $this->insert($in_order);
        $buy_log = [];
        if ($ret !== false) {
            $order_id = $this->getLastInsID();
            $in_order_item = [];
            $goods_ids = [];
            $attribute_ids = [];
            $agency_goods_model = new AgencyGoodsModel();
            $goods_model = new GoodsModel();
            foreach ($goods_data as $value) {
                $goods_source = "agency";
                $ret = -1;
                if (!empty($user_data['agency_id'])) {
                    $agency_store = [
                        'goods_id' => $value['goods_id'],
                        'attribute_ids' => $value['attribute_ids'],
                        'storage' => $value['goods_number'],
                        'target_id' => $user_data['agency_id'],
                    ];
                    $ret = $agency_goods_model->changeStore($agency_store, 'sub', 0, $user_id, true);
                    if ($ret === false) {
                        $this->rollback();
                        $rsps['code'] = 0;
                        $rsps['msg'] = "下单失败成功,代理库存不足";
                        return $rsps;
                    }
                    if (is_numeric($ret)) {
                        if (intval($ret) > 0) {
                            $goods_source = "store";
                            $ret = 0;
                        }
                    }
                }
                if (empty($user_data['agency_id']) || $ret == 0) {
                    $goods_source = "store";
                    $storage = [
                        'storage' => $value['goods_number'],
                        'attribute_ids' => $value['attribute_ids'],
                        'target_id' => 0
                    ];
                    $operate = [
                        'operate' => 'store',
                        'admin_id' => 0
                    ];
                    $ret = $goods_model->changeStore($value['goods_id'], $storage, 'sub', $user_id, $operate, '用户购买平台商品');
                    if ($ret === false) {
                        $this->rollback();
                        $rsps['code'] = 0;
                        $rsps['msg'] = "下单失败成功，商品库存不足";
                        return $rsps;
                    }
                }
                $goods_ids[] = $value['goods_id'];
                $attribute_ids[] = $value['attribute_ids'];
                $in_order_item[] = [
                    'order_id' => $order_id,
                    'user_id' => $user_id,
                    'order_sn' => $order_sn,
                    'goods_id' => $value['goods_id'],
                    'attribute_names' => $value['attribute_names'],
                    'attribute_ids' => $value['attribute_ids'],
                    'goods_special' => $value['goods_special'],
                    'profit_price' => floatval($value['platform_price']) - floatval($value['cost_price']),
                    'cost_price' => $value['cost_price'],
                    'agency_price' => $value['agency_price'],
                    'platform_price' => $value['platform_price'],
                    'goods_price' => $value['goods_price'],
                    'goods_source' => $goods_source,
                    'goods_number' => $value['goods_number'],
                    'agency_id' => $agency_id,
                    'store_id' => $store_id,
                    'goods_type' => $goods_type,
                    'top_user_id' => $top_user_id,//推广用户
                    'top_top_user_id' => $top_top_user_id,//上级推广用户
                    'agency_money' => $value['agency_money'] * intval($value['goods_number']),
                    'return_money' => $value['return_money'] * intval($value['goods_number']),
                    'top_money' => $value['top_money'] * intval($value['goods_number']),//推广用户佣金
                    'top_top_money' => $value['top_top_money'] * intval($value['goods_number']),//上级推广用户佣金
                    'channel_money' => $value['channel_money'] * intval($value['goods_number']),//分享佣金
                    'agency_profit_money' => $value['agency_profit_money'],
                    'order_total' => floatval($value['goods_price']) * intval($value['goods_number']),
                    'channel_id' => $channel,
                    'distributor_id' => $value['distributor_id'],
                ];
                $buy_log[] = [
                    'user_id' => $user_id,
                    'goods_id' => $value['goods_id'],
                    'goods_number' => $value['goods_number'],
                    'nick_name' => $user_data['nick_name'],
                    'head_img' => $user_data['head_img'],
                ];
            }
            if (!empty($in_order_item)) {
                $order_item_model = new OrderItemModel();
                $retx = $order_item_model->saveAll($in_order_item);
                if ($retx !== false) {
                    $user_cart_model = new UserCartModel();
                    $user_cart_model->deleteCartByGoods($goods_ids, $attribute_ids, $user_id);
                    //添加购买记录
                    $ret = GoodsBuyLogModel::addBuyLog($buy_log);
                    if ($ret === true) {
                        $this->commit();
                        $rsps['code'] = 1;
                        $rsps['data'] = [
                            'order_id' => $order_id
                        ];
                        $rsps['msg'] = "下单成功";
                        return $rsps;
                    }
                }
            }
        }
        $this->rollback();
        $rsps['code'] = 0;
        $rsps['msg'] = "下单失败成功";
        return $rsps;
    }

    /**
     * 取消订单
     * @param string $order_id
     * @param string $user_id
     * @param int $store_id
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function cancelOrder($order_id = '', $user_id = '', $store_id = 0)
    {
        $this->startTrans();
        try {
            $map = [
                'id' => $order_id
            ];
            if (!empty($user_id)) {
                $map['user_id'] = $user_id;
            }
            $order_info = $this
                ->storeId($store_id)
                ->where($map)
                ->field("id,order_status")
                ->find();
            if (!isset($order_info['id'])) {
                $this->rollback();
                throw new \think\Exception("订单不存在", 0);
            }
            if ($order_info['order_status'] != 1) {
                $this->rollback();
                throw new \think\Exception("订单状态错误", 0);
            }
            $up_data = [
                'order_status' => 0
            ];
            $ret = $this->where(['id' => $order_id])->update($up_data);
            if ($ret === false) {
                $this->rollback();
                throw new \think\Exception("订单状态更新出错", 0);
            }
            $order_item_model = new OrderItemModel();
            $ret = $order_item_model->cancelOrderStore($order_id);
            if ($ret === true) {
                $this->commit();
                $rsps['code'] = 1;
                return $rsps;
            }
        } catch (\Exception $e) {
            // 回滚事务
            $this->rollback();
            $rsps['code'] = 0;
            $rsps['msg'] = $e->getMessage();
            return $rsps;
        }
        $this->rollback();
        $rsps['code'] = 0;
        $rsps['msg'] = "取消失败";
        return $rsps;
    }

    /**
     * 平台操作支付
     * @param string $order_id
     * @param string $user_id
     * @param int $store_id
     * @return mixed
     */
    public function payOrder($order_id = '', $user_id = '', $store_id = 0)
    {
        $this->startTrans();
        try {
            $map = [
                'id' => $order_id
            ];
            if (!empty($user_id)) {
                $map['user_id'] = $user_id;
            }
            $order_info = $this
                ->storeId($store_id)
                ->where($map)
                ->field("id,order_status")
                ->find();
            if (!isset($order_info['id'])) {
                $this->rollback();
                throw new \think\Exception("订单不存在", 0);
            }
            if ($order_info['order_status'] != 1) {
                $this->rollback();
                throw new \think\Exception("订单状态错误", 0);
            }
            $up_data = [
                'pay_date' => time(),
                'order_status' => 2
            ];
            $ret = $this->where(['id' => $order_id])->update($up_data);
            if ($ret === false) {
                $this->rollback();
                throw new \think\Exception("订单状态更新出错", 0);
            }
            $order_item_model = new OrderItemModel();
            $ret = $order_item_model->payOrder($order_id);
            if ($ret['code'] === 1) {
                $this->commit();
                $rsps['code'] = 1;
                return $rsps;
            }
        } catch (\Exception $e) {
            // 回滚事务
            $this->rollback();
            $rsps['code'] = 0;
            $rsps['msg'] = $e->getMessage();
            return $rsps;
        }
        $this->rollback();
        $rsps['code'] = 0;
        $rsps['msg'] = "付款失败";
        return $rsps;
    }

    /**
     * 订单退款
     * @param string $order_id
     * @param array $item_ids
     * @param bool $is_group
     * @param int $store_id
     * @return array|bool|mixed|string
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function refundOrder($order_id = '', $item_ids = [], $is_group = false, $store_id = 0)
    {
        $map = [
            'id' => $order_id
        ];
        $order_temp = $this->storeId($store_id)->where($map)->where('order_status', '>=', 2)->find();
        if (empty($order_temp)) {
            if ($is_group) {
                return true;
            }
            throw new \think\Exception("订单信息不存在", 0);
        }
        $pay_sn_old = $order_temp['pay_sn'];
        $order_sn = $order_temp['order_sn'];
        $pay_mode = $order_temp['pay_mode'];
        $order_item_model = new OrderItemModel();
        $order_items_temp = $order_item_model->getItemsInfo($order_id, $item_ids);
        $goods_ids = [];
        $refund_total = floatval($order_temp['freight_price']);
        foreach ($order_items_temp as $value) {
            if (intval($value['goods_special']) == 0) {
                $refund_total += floatval($value['order_total']);
                $goods_ids[] = $value['goods_id'];
            }
        }
        $refund_total = floatval($refund_total);
        if ($refund_total == 0) {
            return true;
        }
        if (empty($goods_ids)) {
            throw new \think\Exception("商品信息不存在", 0);
        }
        $pay_info = PayLogModel::getPayLog($order_sn, 'pay');
        if (!isset($pay_info['pay_sn'])) {
            return false;
        }
        if (intval($pay_info['status']) == 0) {
            return true;
        }
        $order_total = PayLogModel::getLogTotal($pay_sn_old);
        if (empty($item_ids)) {
            $refund_total = $order_total;
        } else {
            $refund_total = OrderItemModel::getRefundMoney($order_id);
        }
        $pay_sn = "refund" . date("YmdHis") . $order_temp['id'] . mt_rand(1000, 9999);
        $pay_log['order_sn'] = $order_sn;
        $pay_log['pay_sn'] = $pay_sn;
        $pay_log['total'] = $refund_total;
        PayLogModel::addLog($pay_log, 'refund', $pay_mode);
        //刷新项订单状态
        $ret = $order_item_model->refundEndByGoodsId($order_id, $goods_ids);
        if ($ret !== false) {
            //清除预结算
            OrderItemModel::clearEarnings($order_id);
            $out_data['out_refund_no'] = $pay_sn;//退款订单号-新
            $out_data['out_trade_no'] = $pay_sn_old;//支付订单号-旧
            $out_data['refund_fee'] = $refund_total;//退款金额
            $out_data['total_fee'] = $order_total;//订单金额
            if ($refund_total > $order_total) {
                throw new \think\Exception("退款金额大于订单金额", 0);
            }
            if ($pay_mode == 'weixin') {
                //访问退款接口
                $WxOut = new WxOut();
                $res = $WxOut->confirm($out_data);
                if ($res['return_code'] == "SUCCESS" && $res['result_code'] == "SUCCESS") {
                    return true;
                }
            } else if ($pay_mode == 'balance') {
                $user_model = new UserModel();
                $return_data = $user_model->changePayPrice($order_temp['user_id'], floatval($refund_total), 'refund');
                if (!empty($return_data['code'])) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     *更新操作状态
     * @param $order_id
     * @param $item_ids
     * @param $out_handle_status
     * @param $out_type
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function handleStatus($order_id, $item_ids, $out_handle_status, $out_type = 2)
    {
        $up_data = [
            'out_handle_status' => $out_handle_status,
            'out_type' => $out_type
        ];
        $order_item_model = new OrderItemModel();
        $this->startTrans();
        $order_item_model->startTrans();
        $retx = $order_item_model->where('id', 'in', $item_ids)->update($up_data);
        $ret = $this->where(['id' => $order_id])->update($up_data);
        if ($ret !== false && $retx !== false) {
            $this->commit();
            $order_item_model->commit();
            return true;
        }
        $this->rollback();
        $order_item_model->rollback();
        return false;
    }

    /**
     * 设置实际收款金额
     * @param $order_id
     * @param $actual_price
     * @param $store_id
     * @return mixed
     */
    public function handleOrderStatus($order_id, $actual_price, $store_id = 0)
    {
        $this->startTrans();
        $res = $this->storeId($store_id)->where('id', $order_id)->update(['actual_price' => $actual_price]);
        $rsps = $this->payOrder($order_id);
        if ($res && $rsps['code'] == 1) {
            $this->commit();
            $rsps['code'] = 1;
            $rsps['msg'] = "收款成功";
            return $rsps;
        } else {
            $this->rollback();
            $rsps['code'] = 0;
            $rsps['msg'] = "收款失败，请检查网络";
            return $rsps;
        }
    }

    /**
     * 设置订单各项价格
     * @param $id
     * @param $price freight运费，difference差价，actual实际收款，cost实际成本
     * @param $store_id
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function setOrderPrice($id, $price, $store_id = 0)
    {
        $res['code'] = 0;
        $res['msg'] = "更改失败";
        if (empty($id) || empty($price)) {
            return $res;
        }
        $order_data = $this->where('id', $id)->storeId($store_id)->field('order_status')->find();
        if (empty($order_data)) {
            $res['code'] = 10;
            $res['msg'] = "更改失败";
            return $res;
        }
        $up_data = [];
        if (intval($order_data['order_status']) == 1) {
            if (isset($price['freight'])) {
                $up_data['freight_price'] = floatval($price['freight']) > 0 ? $price['freight'] : 0;
            }
            if (isset($price['difference'])) {
                $up_data['difference_price'] = $price['difference'];
            }
//            $up_data['actual_price'] = $price['actual'];
        }
        if (isset($price['cost'])) {
            $up_data['cost_price'] = $price['cost'];
        }
        if (empty($up_data)) {
            return $res;
        }
        $ret = $this->where('id', $id)->update($up_data);
        if ($ret !== false) {
            $order_id_key = str_replace('_', '', $id);
            Cache::store('redis')->set($this->redis_key . 'pay' . $order_id_key, "", 2);
            $res['code'] = 1;
            $res['msg'] = "更改成功";
        }
        return $res;
    }

    /**
     * 修改收货地址
     * @param $id
     * @param $phone
     * @param $name
     * @param $address
     * @param $store_id
     * @return mixed
     */
    public function setTakeAddress($id, $phone, $name, $address, $store_id = 0)
    {
        $res['code'] = 0;
        $res['msg'] = "更改失败";
        if (empty($id) || empty($phone) || empty($name) || empty($address)) {
            return $res;
        }
        $order_data = $this->where('id', $id)->storeId($store_id)->field('order_status')->find();
        if (empty($order_data)) {
            $res['code'] = 10;
            $res['msg'] = "更改失败";
            return $res;
        }
        $up_data = [
            'take_address' => $address,
            'take_name' => $name,
            'take_phone' => $phone
        ];
        $ret = $this->where('id', $id)->update($up_data);
        if ($ret !== false) {
            $res['code'] = 1;
            $res['msg'] = "更改成功";
        }
        return $res;
    }

    /**
     * 修改物流单号
     * @param $id
     * @param array $logistics_numbers
     * @param int $store_id
     * @return mixed
     * @throws \Exception
     */
    public function setLogisticsNumber($id, $logistics_numbers = [], $store_id = 0)
    {
        $res['code'] = 0;
        $res['msg'] = "更改失败";
        if (empty($logistics_numbers)) {
            return $res;
        }
        $order_data = $this->where('id', $id)->storeId($store_id)->field('order_status')->find();
        if (empty($order_data)) {
            $res['code'] = 10;
            $res['msg'] = "更改失败";
            return $res;
        }
        $up_data = [];
        foreach ($logistics_numbers as $value) {
            $up_data[] = [
                'id' => $value['id'],
                'logistics_code' => $value['logistics_code'],
                'logistics_number' => $value['logistics_number']
            ];
        }
        $order_logistics_model = new OrderItemLogisticsModel();
        $ret = $order_logistics_model->saveAll($up_data);
        if ($ret !== false) {
            $res['code'] = 1;
            $res['msg'] = "更改成功";
        }
        return $res;
    }

    /**
     * 获取当前用户最近订单坐标
     * @param $goods_id
     * @param $lng
     * @param $lat
     * @return array
     */
    public function getAbsOrder($goods_id, $lng, $lat)
    {
        $sql = "SELECT a.order_lng,a.order_lat,abs($lng-a.order_lng)+abs($lat-a.order_lat) as distance FROM t_order a 
                JOIN t_order_item b ON a.id=b.order_id
                WHERE b.goods_id=$goods_id
                ORDER BY distance ASC limit 1";
        return Db::query($sql);
    }

    /**
     * 获取支付信息
     * @param string $order_id
     * @param string $user_id
     * @param string $pay_mode
     * @return array
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getOrderPayInfo($order_id, $user_id, $pay_mode = 'weixin')
    {
        if (empty($order_id) || empty($user_id)) {
            throw new \think\Exception("订单支付参数有误", 0);
        }
        $order_ids = [];
        if (strpos($order_id, '_') > 0) {
            $order_ids = explode('_', $order_id);
        } else {
            $order_ids[] = $order_id;
        }
        $order_id_key = str_replace('_', '', $order_id);
        $pay_sn = Cache::store('redis')->get($this->redis_key . 'pay' . $order_id_key, 0);
        if (empty($pay_sn)) {
            $pay_sn = "pay" . date("YmdHis") . rand(100, 999) . rand(100, 999);
            Cache::store('redis')->set($this->redis_key . 'pay' . $order_id_key, $pay_sn, 600);
        }
        Db::startTrans();
        $order_total_all = 0;
        $ret = false;
        $retx = false;
        foreach ($order_ids as $value) {
            $map = [
                'id' => $value,
                'user_id' => $user_id,
                'order_status' => 1
            ];
            $order_data = $this->where($map)->field('id,order_sn,freight_price,coupon_id,order_total,difference_price')->find();
            if (empty($order_data)) {
                throw new \think\Exception("订单支付信息有误", 0);
            }
            $order_sn = $order_data['order_sn'];
            $freight_price = floatval($order_data['freight_price']);
            $difference_price = floatval($order_data['difference_price']);
            $order_total = 0;
            $order_total += floatval($order_data['order_total']);
            $order_total += $freight_price + $difference_price;
            if (!empty($order_data['coupon_id'])) {
                $coupon_price = UserCouponModel::getCouponPrice($user_id, $order_data['coupon_id']);
                $order_total = $order_total - $coupon_price;
            }

            $up_pay = [
                'pay_sn' => $pay_sn
            ];
            $ret = $this->where($map)->update($up_pay);
            $order_item_model = new OrderItemModel();
            $map = [
                'order_id' => $value
            ];
            $retx = $order_item_model->where($map)->update($up_pay);
            $in_data = [
                'order_id' => $value,
                'order_sn' => $order_sn,
                'pay_sn' => $pay_sn,
                'total' => $order_total
            ];
            PayLogModel::addLog($in_data, "pay", $pay_mode);
            $order_total_all += $order_total;
        }
        $out_data = [
            'order_id' => $order_id,
            'pay_sn' => $pay_sn,
            'total' => $order_total_all
        ];
        if ($ret !== false && $retx !== false) {
            Db::commit();
        } else {
            Db::rollback();
            return [];
        }
        return $out_data;
    }

    /**
     * 完成支付
     * @param $pay_sn
     * @param $pay_mode
     * @return array|bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function endOrderPay($pay_sn, $pay_mode)
    {
        $map = [
            'pay_sn' => $pay_sn
        ];
        $order_data = $this->where($map)->field('id,user_id,bean,coupon_id,freight_price,goods_type,order_total')->find();
        $up_pay = [
            'order_status' => 2,
            'actual_price' => $order_data['order_total'] + $order_data['freight_price'],
            'pay_date' => time()
        ];
        if ($pay_mode == "balance") {
            $user_model = new UserModel();
            $return_data = $user_model->changePayPrice($order_data['user_id'], floatval($order_data['order_total']), 'pay');
            if (empty($return_data['code'])) {
                return $return_data;
            }
        }
        $coupon_price = 0;
        if (!empty($order_data['coupon_id'])) {
            $coupon_price = UserCouponModel::getCouponPrice($order_data['user_id'], $order_data['coupon_id']);
            $ret = UserCouponModel::useCoupon($order_data['user_id'], $order_data['coupon_id']);
            if ($ret == false) {
                $return_data = [
                    'code' => 0,
                    'msg' => "兑换券使用失败"
                ];
                UserCouponModel::cancelCoupon($order_data['user_id'], $order_data['coupon_id']);
                return $return_data;
            }
        }
        if ($pay_mode == 'bean') {
            $all_price = $order_data['order_total'] + $order_data['freight_price'];
            $bean_price = ($all_price - $coupon_price);
            $ratio = Config::get('system.ratio');
            $bean = ceil($bean_price / $ratio);
            $return_data = UserBeanLogModel::changeEarningsBean($order_data['user_id'], $bean, 'use', "商品兑换 ");
            if (empty($return_data['code'])) {
                return $return_data;
            }
        }
        $this->startTrans();
        $ret = $this->where($map)->update($up_pay);
        if ($ret !== false) {
//            UserModel::costSum($order_data['user_id'], $order_data['order_total']);
            if ($pay_mode != 'bean' && intval($order_data['goods_type']) == 0) {
                //刷新消费
                UserModel::costSum($order_data['user_id'], $order_data['order_total']);
                //订单预结算
                $day = date("Y-m-d");
                UserModel::upOrderNow($order_data['id'], $day);
            }
            if ($pay_mode == 'weixin') {
                if (intval($order_data['goods_type']) == 2) {
                    //综合商城 支付获取趣豆
                    $pay_price = floatval($order_data['order_total']) + floatval($order_data['freight_price']) - $coupon_price;
                    $order_ratio = Config::get('system.order_ratio');
                    $bean = $pay_price * $order_ratio;
                    UserBeanLogModel::changeEarningsBean($order_data['user_id'], $bean, "recharge", "购买商品赠送");
                }
            }
            $order_item_model = new OrderItemModel();
            unset($up_pay['actual_price']);
            $ret = $order_item_model->where($map)->update($up_pay);
            if ($ret !== false) {
                if (intval($order_data['goods_type']) == 3) {
                    //刷新特殊商品（大礼包，趣豆---商品券）
                    $order_item_model->upDateGoodsSpecial($order_data['id'], 3);
                }

                $this->commit();
                $return_data['code'] = 1;
                $return_data['msg'] = "支付成功";
                return $return_data;
            } else {
                $this->rollback();
            }
        }
        $this->rollback();
        $return_data['code'] = 0;
        $return_data['msg'] = "支付失败";
        return $return_data;
    }

    /**
     * 确认收货
     * @param $order_id
     * @param $user_id
     * @param bool $is_system
     * @param int $store_id
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function confirmTake($order_id, $user_id, $is_system = false, $store_id = 0)
    {
        if (empty($order_id)) {
            $rsps['code'] = 0;
            $rsps['msg'] = "参数有误";
            return $rsps;
        }
        $map = [
            'id' => $order_id
        ];
        if (!$is_system) {
            if (empty($user_id)) {
                $rsps['code'] = 0;
                $rsps['msg'] = "参数有误";
                return $rsps;
            }
            $map['user_id'] = $user_id;
        }
        $this->startTrans();
        $order = $this->storeId($store_id)->where($map)->field("id,order_status")->find();
        if (!isset($order['id'])) {
            $this->rollback();
            $rsps['code'] = 0;
            $rsps['msg'] = "订单不存在";
            return $rsps;
        }
        if (!($order['order_status'] == 2 || $order['order_status'] == 3)) {
            $this->rollback();
            $rsps['code'] = 0;
            $rsps['msg'] = "订单状态错误";
            return $rsps;
        }
        $up['order_status'] = 4;
        $up['take_time'] = time();
        $order_item_model = new OrderItemModel();
        $order_item_model->where('order_id', $order['id'])->update($up);
        $up['take_date'] = date("Y-m-d H:i:s");
        $this->where("id", $order['id'])->update($up);
        $this->commit();
        $rsps['code'] = 1;
        return $rsps;
    }

    /**
     * 申请退款/退货
     * @param $order_id
     * @param $item_id
     * @param $out_explain
     * @param $user_id
     * @param $store_id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function outOrder($order_id, $item_id, $out_explain, $user_id, $store_id = 0)
    {
        if (empty($order_id) || empty($item_id) || empty($out_explain) || empty($user_id)) {
            $return_data['code'] = 0;
            $return_data['msg'] = "参数有误";
            return $return_data;
        }
        $this->startTrans();
        $OrderItemModel = new OrderItemModel();
        $map = [
            'id' => $order_id,
            'user_id' => $user_id
        ];
        $order = $this->storeId($store_id)->where($map)->where('out_handle_status', '=', 0)->field("id,order_status")->find();
        $map = [
            'order_id' => $order_id,
            'user_id' => $user_id
        ];
        if (!isset($order['id'])) {
            $return_data = [
                'code' => 0,
                'msg' => '订单不存在'
            ];
            return $return_data;
        }
        $out_type = 2;
        if (intval($order['order_status']) == 2) {
            $out_type = 1;
        }
        if (strpos($item_id, ',') === false) {
            $map['id'] = $item_id;
            $order_item = $OrderItemModel->where($map)->where('order_status', 'between', '2,3')->field('id,order_status')->find();
            if (!isset($order_item['id'])) {
                $return_data = [
                    'code' => 0,
                    'msg' => '订单商品不存在'
                ];
                return $return_data;
            }
            $up_order_item['out_type'] = $out_type;//类型
            $up_order_item['out_handle_status'] = 1;//是否审核
            $ret = $this->where("id", $order_id)->update(['out_handle_status' => 1]);
            $retx = $OrderItemModel->where("id", $item_id)->update($up_order_item);
            $item_ids = [
                $item_id
            ];
        } else {
            $item_ids = explode(',', $item_id);
            $order_items = $OrderItemModel->where($map)->where('id', 'in', $item_id)
                ->where('order_status', 'between', '2,3')
                ->field('id,order_status')->select();
            if ($order_items->isEmpty()) {
                $return_data = [
                    'code' => 0,
                    'msg' => '订单商品不存在'
                ];
                return $return_data;
            }
            $up_order_item['out_type'] = $out_type;//类型
            $up_order_item['out_handle_status'] = 1;//是否审核
            $ret = $this->where("id", $order_id)->update(['out_handle_status' => 1]);
            $retx = $OrderItemModel->where('id', 'in', $item_id)->update($up_order_item);
        }
        if ($ret !== false && $retx !== false) {
            $order_item_out_model = new OrderItemOutModel();
            $out_order = [
                'id' => $order_id,
                'item_ids' => $item_ids,
                'out_type' => $out_type
            ];
            $ret = $order_item_out_model->addOutOrder($out_order, $out_explain);
            if ($ret['code'] == 1) {
                $return_data = [
                    'code' => 1,
                    'msg' => '申请退款成功'
                ];
                $this->commit();
            } else {
                $return_data = $ret;
            }
            return $return_data;
        }
        $this->rollback();
        $return_data = [
            'code' => 0,
            'msg' => '申请退款失败'
        ];
        return $return_data;
    }

    /**
     * 获取单条数据
     * @param $id
     * @param string $field
     * @param int $store_id
     * @return array|Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getChildInfo($id, $field = '*', $store_id = 0)
    {
        $data = $this
            ->alias("a")
            ->storeId($store_id)
            ->leftJoin("t_user b", "a.user_id=b.id")
            ->leftJoin("t_agency c", "a.agency_id=c.id")
            ->field($field)
            ->where('a.id', $id)
            ->find();
        //订单项
        $order_item_model = new OrderItemModel();
        if (empty($data)) {
            return [];
        }
//        $data['order_items'] = $order_item_model->getChildInfo($data['id']);
        $order_items = $order_item_model->getChildInfo($data['id']);
        foreach ($order_items as &$value) {
            $value['total_cost_price'] = floatval($value['cost_price']) * $value['goods_number'];
        }
        $data['order_items'] = $order_items;
        $order_item_logistics_model = new OrderItemLogisticsModel();
        $data['logistics_numbers'] = $order_item_logistics_model->getChildInfo($data['id']);
        if (!empty($data['freight_price'])) {
            $data['order_total'] += floatval($data['freight_price']) + floatval($data['difference_price']);
        }
        return $data;
    }

    /**
     * 获取退款订单信息
     * @param $id
     * @param string $field
     * @param int $store_id
     * @return array|Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getOutInfo($id, $field = 'a.*,b.nick_name,c.agency_title', $store_id = 0)
    {
        $order_data = $this->alias("a")
            ->storeId($store_id)
            ->leftJoin("t_user b", "a.user_id=b.id")
            ->leftJoin("t_agency c", "a.agency_id=c.id")
            ->field($field)
            ->where('a.id', $id)
            ->find();
        $order_item_model = new OrderItemModel();
        $order_item_out_model = new OrderItemOutModel();
        $out_order = $order_item_out_model->getOutInfo($id);
        $item_ids = unserialize($out_order['item_ids']);
        $items = $order_item_model->getItemsInfo($id, $item_ids, []);
        if (!empty($order_data['pay_date'])) {
            $order_data['pay_date'] = date("Y-m-d H:i:s", $order_data['pay_date']);
        }

        $data['order'] = $order_data;
        $data['out_order'] = $out_order;
        $data['items'] = $items;
        return $data;
    }

    /**
     * 获取时间范围数据
     * @param $begin
     * @param $end
     * @param $store_id
     * @return \think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getDataByBetweenDt($begin, $end, $store_id = 0)
    {
        return $this->storeId($store_id)->where('order_status', '>', 2)->whereBetweenTime('create_date', $begin, $end)->field("create_date_day as create_date,SUM(order_total) as order_total")->group("create_date_day")->select();
    }

    /**
     * 获取退款订单数
     * @param int $store_id
     * @return mixed
     */
    public function getOutCount($store_id = 0)
    {
        //
        $data = $this
            ->alias("a")
            ->storeId($store_id)
            ->Join("t_order_item b", "a.id=b.order_id")
            ->Join("t_goods c", "b.goods_id=c.id")
            ->where('b.out_type', 2)//已申请退款
            ->count();
        return $data;
    }

    /**
     * 获取订单物流信息
     * @param $order_id
     * @param $item_id
     * @param $type
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getOrderLogistics($order_id, $item_id = '', $type = 'list')
    {
        $order_item_logistics_model = new OrderItemLogisticsModel();
        if ($type == 'one') {
            $map = [
                'id' => $item_id
            ];
            $logistics = $order_item_logistics_model->where($map)->find();
            $rsps['data']['logistics'] = $logistics;
        } else {
            $logistics_list = $order_item_logistics_model->where('order_id', $order_id)->select();
            $logistics = [];
            foreach ($logistics_list as &$value) {
                $value['item_list'] = json_decode($value['order_item_info'], true);
                if (empty($item_id)) {
                    $logistics = $logistics_list[0];
                } else {
                    if ($value['id'] == $item_id) {
                        $logistics = $value;
                    }
                }
            }
            if ($logistics_list->isEmpty()) {
                $rsps['code'] = 1;
                $rsps['data']['traces'] = [
                    [
                        'AcceptStation' => "物流信息不存在",
                        'AcceptTime' => date("Y-m-d H:i:s")
                    ]
                ];
                $rsps['msg'] = "物流信息不存在";
                return $rsps;
            }
            $rsps['data']['list'] = $logistics_list;
        }
        $Logistics_tool = new Logistics();
        $take_phone = "";
        if ($logistics['logistics_code'] == "SF") {
            $take_phone = OrderModel::getTakePhone($logistics['order_id']);
        }
        $logistics_log = json_decode($Logistics_tool->getOrderTracesByJson($logistics['order_id'], $logistics['logistics_code'], $logistics['logistics_number'], $take_phone), true);
        if (empty($logistics_log['Traces'])) {
            $rsps['data']['traces'] = [
                [
                    'AcceptStation' => "暂无物流信息",
                    'AcceptTime' => date("Y-m-d H:i:s")
                ]
            ];
        } else {
            $rsps['data']['traces'] = array_reverse($logistics_log['Traces']);
        }
        $rsps['code'] = 1;
        $rsps['msg'] = "获取成功";
        return $rsps;
    }

    /**
     * 获取用户返现收益预估
     * @param $user_id
     * @return int
     */
    public function getFifteenFx($user_id)
    {
        $order_item_model = new OrderItemModel();
        $map = [
            'user_id' => $user_id,
            'out_handle_status' => 0
        ];
        $return_money = $order_item_model->where($map)->betweenStatus("2,4")->sum('return_money');
        if (empty($return_money)) {
            $return_money = 0;
        }
        return $return_money;
    }

    /**
     * 获取用户佣金预估-下级贡献
     * @param $user_id
     * @return int
     */
    public function getFifteenYj($user_id)
    {
        $order_item_model = new OrderItemModel();
        $map = [
            'top_user_id' => $user_id,
            'out_handle_status' => 0
        ];
        $top_money = $order_item_model->where($map)->betweenStatus("2,4")->sum('top_money');
        if (empty($top_money)) {
            $top_money = 0;
        }
        $map = [
            'top_top_user_id' => $user_id,
            'out_handle_status' => 0
        ];
        $top_money += $order_item_model->where($map)->betweenStatus("2,4")->sum('top_top_money');
        $map = [
            'channel_id' => $user_id,
            'out_handle_status' => 0
        ];
        $top_money += $order_item_model->where($map)->betweenStatus("2,4")->sum('channel_money');
        return round($top_money, 2);
    }

    /**
     * 获取代理商预估利润
     * @param $agency_id
     * @return int
     */
    public function getAgencyFifteenLy($agency_id)
    {
        $map = [
            'agency_id' => $agency_id,
            'out_handle_status' => 0,
            'goods_source' => "agency"
        ];
        $order_item_model = new OrderItemModel();
        $agency_profit_money = $order_item_model->where($map)->betweenStatus("1,4")->sum('agency_profit_money');
        if (empty($agency_profit_money)) {
            $agency_profit_money = 0;
        }
        return $agency_profit_money;
    }

    /**
     * 获取代理商佣金总和
     * @param $agency_id
     * @return int
     */
    public function getAgencyYj($agency_id)
    {
//        $sql = "select SUM(b.agency_money) as agency_money from t_order a JOIN t_order_item b on a.id=b.order_id and b.out_status=2
//                WHERE a.order_status<=4 AND a.order_agency_id=$agency_id";
//
//        return Db::query($sql)[0];
        $map = [
            'agency_id' => $agency_id,
            'out_handle_status' => 0
        ];
        $order_item_model = new OrderItemModel();
        $agency_money = $order_item_model->where($map)->where('agency_money', '>', 0)->where('order_status', '>', 1)->sum('agency_money');
        if (empty($agency_money)) {
            $agency_money = 0;
        }
        return $agency_money;
    }

    /**
     * 获取商家收益
     * @param $store_id
     * @return int
     */
    public function getStoreEarnings($store_id = 0)
    {
        $map = [
            'store_id' => $store_id,
            'out_handle_status' => 0
        ];
        $order_model = new OrderModel();
        $order_total = $order_model->where($map)->betweenStatus("1,4")->sum('order_total');
        if (empty($order_total)) {
            $order_total = 0;
        }
        $freight_price = $order_model->where($map)->betweenStatus("1,4")->sum('freight_price');
        if (empty($freight_price)) {
            $freight_price = 0;
        }
        return $order_total + $freight_price;
    }

    /**
     * 获取代理商今日订单数量
     * @param $agency_id
     * @return int
     */
    public function getAgencyToDayOrder($agency_id)
    {
        $map = [
            'agency_id' => $agency_id
        ];
        $to_day_order = $this->where($map)->count('id');
        if (empty($to_day_order)) {
            $to_day_order = 0;
        }
        return $to_day_order;
    }

    /**
     * 本月订单统计
     * @param $agency_id
     * @param string $day
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getAgencyToMonthOrder($agency_id, $day = "")
    {
        $map = [
            'agency_id' => $agency_id,
            'out_type' => 0
        ];

        if (empty($day)) {
            $day_start = date("Y-m-") . "01 00:00:00";
            $day_end = date("Y-m-d") . " 24:59:59";
        } else {
            $day_start = $day . "-01 00:00:00";
            $day_end = date("Y-m-t", strtotime($day . "-01 00:00:00")) . " 24:59:59";
        }
        $time_start = strtotime($day_start);
        $time_end = strtotime($day_end);
        $last_start = strtotime(date("Y-m-d", strtotime($day_start . " -1 month")));
        $last_end = strtotime(date("Y-m-d", strtotime($day_end . " -1 month")));
        $order_model = new OrderModel();
        $user_model = new UserModel();
        $order_data['order_count'] = $order_model->where($map)->where('order_status', '>', 1)->whereBetween('create_time', $time_start . "," . $time_end)->count('id');
        $order_last_data['order_count'] = $order_model->where($map)->where('order_status', '>', 1)->whereBetween('create_time', $last_start . "," . $last_end)->count('id');
        $order_data['agency_profit'] = OrderModel::getAgencyEarnings($agency_id, $time_start, $time_end, 2);
        $order_last_data['agency_profit'] = OrderModel::getAgencyEarnings($agency_id, $last_start, $last_end, 2);
        $popularize_count = $user_model->where('agency_id', $agency_id)->whereBetween('agency_time', $time_start . "," . $time_end)->count('id');
        if (empty($popularize_count)) {
            $popularize_count = 0;
        }
        $last_popularize_count = $user_model->where('agency_id', $agency_id)->whereBetween('agency_time', $last_start . "," . $last_end)->count('id');
        if (empty($last_popularize_count)) {
            $last_popularize_count = 0;
        }
        return [
            'count' => $order_data['order_count'],
            'last_count' => $order_last_data['order_count'],
            'count_status' => Util::getCompare($order_data['order_count'], $order_last_data['order_count']),
            'agency_profit' => $order_data['agency_profit'],
            'last_agency_profit' => $order_last_data['agency_profit'],
            'agency_profit_status' => Util::getCompare($order_data['agency_profit'], $order_last_data['agency_profit']),
            'popularize_count' => $popularize_count,
            'last_popularize_count' => $last_popularize_count,
            'popularize_count_status' => Util::getCompare($popularize_count, $last_popularize_count)
        ];
    }

    /**
     * 获取代理商待付款订单
     * @param $agency_id
     * @return int
     */
    public function getAgencyDfkOrder($agency_id)
    {
//        $sql = "SELECT count(id) as counts FROM t_order WHERE order_status=1 AND order_agency_id=$agency_id";
//        return Db::query($sql)[0];
        $map = [
            'agency_id' => $agency_id,
            'order_status' => 1
        ];
        $dfk_order = $this->where($map)->count('id');
        if (empty($dfk_order)) {
            $dfk_order = 0;
        }
        return $dfk_order;
    }

    /**
     * 获取代理商待发货订单
     * @param $agency_id
     * @return int
     */
    public function getAgencyDfhOrder($agency_id)
    {
//        $sql = "SELECT count(id) as counts FROM t_order WHERE order_status=2 AND order_agency_id=$agency_id";
//        return Db::query($sql)[0];
        $map = [
            'agency_id' => $agency_id,
            'order_status' => 2
        ];
        $dfk_order = $this->where($map)->count('id');
        if (empty($dfk_order)) {
            $dfk_order = 0;
        }
        return $dfk_order;
    }

    /**
     * 获取代理商未处理售后
     * @param $agency_id
     * @return int
     */
    public function getAgencyOutOrder($agency_id)
    {
//        $sql = "SELECT count(a.id) as counts
//            FROM t_order a JOIN t_order_item b ON a.id=b.order_id and b.out_status=1 and b.out_handle_status=1
//            WHERE a.order_agency_id=$agency_id";
//        return Db::query($sql)[0];
        $map = [
            'agency_id' => $agency_id,
            'out_handle_status' => 1
        ];
        $order_item_model = new OrderItemModel();
        $out_order = $order_item_model->where($map)->betweenStatus("1,4")->count('id');
        if (empty($out_order)) {
            $out_order = 0;
        }
        return $out_order;
    }

    /**
     * 自动任务-发货的商品7天自动收货
     * @return bool
     */
    public function updateTask()
    {
//        $map = ['order_status' => 2, 'out_handle_status' => 0];
//        $day_15 = time() - (3600 * 24 * 15);
        $day_7 = time() - (3600 * 24 * 7);
        $day = date("Y-m-d H:i:s");
        $time = time();
        $up_data = [
            'order_status' => 4,
            'take_date' => $day,
            'take_time' => $time
        ];
        $map = [
            'out_handle_status' => 0
        ];
        $this->where($map)->whereIn('order_status', [2, 3])->where('create_time', '<=', $day_7)->update($up_data);
        //更新订单状态
        $order_item_model = new OrderItemModel();
        $up_item_data = [
            'order_status' => 4,
            'take_time' => $time
        ];
        $ret = $order_item_model->where($map)->whereIn('order_status', [2, 3])->where('create_time', '<=', $day_7)->update($up_item_data);
        if ($ret !== false) {
            return true;
        }
        return false;
    }

    /**
     * 获取订单数量统计
     *
     * @param [type] $user_id
     * @return void
     */
    public function getOrderStatis($user_id)
    {
        $data = $this
            ->field('count(id) as z_count,if(order_status=1,count(id),0) as dfk_count,if(order_status=2,count(id),0) as dfh_count,if(order_status=3,count(id),0) as dsh_count,if(out_type=1,count(id),0) as zy_count')
            ->where('user_id', $user_id)
            ->find();
        return $data;
    }

    /**
     * 获取用户情况
     * @param array $user_ids
     * @param int $time_start
     * @param int $time_end
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getUserListPop($user_ids = [], $time_start, $time_end)
    {
        $order_list = $this->whereIn('user_id', $user_ids)
            ->where('create_time', '>=', $time_start)
            ->where('create_time', '<=', $time_end)
            ->where('order_status', '>=', 2)
            ->where('pay_date', '>=', 0)
            ->where('pay_date', '>=', 0)
            ->where('out_type', '=', 0)
            ->where('goods_type', '=', 0)
            ->field('id,SUM(order_total) as all_order_total,user_id')
            ->group('user_id')
            ->select();

        $user_data = [];
        foreach ($order_list as $value) {
            if (!isset($user_data[intval($value['user_id'])])) {
                $user_data[intval($value['user_id'])]['total'] = 0;
                $user_data[intval($value['user_id'])]['order_ids'] = [];
                $user_data[intval($value['user_id'])]['total'] += $value['all_order_total'];
                $user_data[intval($value['user_id'])]['order_ids'][] = $value['id'];
            } else {
                $user_data[intval($value['user_id'])]['total'] += $value['all_order_total'];
                $user_data[intval($value['user_id'])]['order_ids'][] = $value['id'];
            }
        }
        foreach ($user_ids as $value) {
            if (!isset($user_data[intval($value)])) {
                $user_data[intval($value)]['total'] = 0;
                $user_data[intval($value)]['order_ids'] = [];
            }
        }
        return $user_data;
    }


    /**
     * 获取用户情况
     * @param array $user_ids
     * @param int $time_start
     * @param int $time_end
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getUserListPopSum($user_ids = [])
    {
        $time_start = strtotime("2022-10-09");
        $time_end = time();
        $order_list = $this->whereIn('user_id', $user_ids)
            ->where('create_time', '>=', $time_start)
            ->where('create_time', '<=', $time_end)
            ->where('order_status', '>=', 2)
            ->where('pay_date', '>=', 0)
            ->where('out_type', '=', 0)
            ->where('goods_type', '=', 0)
            ->field('id,SUM(order_total) as all_order_total,user_id')
            ->group('user_id')
            ->select();

        $user_data = [];
        foreach ($order_list as $value) {
            if (!isset($user_data[intval($value['user_id'])])) {
                $user_data[intval($value['user_id'])]['total'] = 0;
                $user_data[intval($value['user_id'])]['order_ids'] = [];
                $user_data[intval($value['user_id'])]['total'] += $value['all_order_total'];
                $user_data[intval($value['user_id'])]['order_ids'][] = $value['id'];
            } else {
                $user_data[intval($value['user_id'])]['total'] += $value['all_order_total'];
                $user_data[intval($value['user_id'])]['order_ids'][] = $value['id'];
            }
        }
        foreach ($user_ids as $value) {
            if (!isset($user_data[intval($value)])) {
                $user_data[intval($value)]['total'] = 0;
                $user_data[intval($value)]['order_ids'] = [];
            }
        }
        return $user_data;
    }


    /**
     * 获取订单统计
     * @param $timeStr
     * @param $field
     * @param $order
     * @param $current_page
     * @param $list_rows
     * @return array
     */
    public function getOrderAnalysis($timeStr, $field, $order, $current_page, $list_rows)
    {
        $order_str = $field . " " . $order;
        $dataList = $this
            ->alias('a')
            ->field('a.create_date_day,count(if(a.order_status>=2, 1, null)) as pay_count,count(if(a.order_status=0,1,null)) as cancel_count,sum(if(a.order_status>=2,a.order_total,0)) as sell_price,(sum(if(a.order_status>=2,a.actual_price,0))-sum(if(a.order_status>=2,a.cost_price,0))) as gain_price')
            ->group('a.create_date_day')
            ->time($timeStr)
            ->order($order_str)
            ->paginate(['page' => $current_page, 'list_rows' => $list_rows], false);
        $current = $dataList->currentPage();
        $total = $dataList->total();
        $limit = $dataList->listRows();
        $items = $dataList->items();
        foreach ($items as &$value) {
            $value['gain_price'] = OrderModel::getDayProfit($value['create_date_day']);
        }
        $ret = ['total' => $total, 'current' => $current, 'limit' => $limit, 'dataList' => $items];
        return $ret;
    }

    /**
     * 计算全部用户的累计消费额度
     * @param array $user_ids
     * @param $time_start
     * @param $time_end
     * @return float|int
     */
    public static function getUserListCons($user_ids = [], $time_start, $time_end)
    {
        $order_total = self::whereIn('user_id', $user_ids)
            ->where('create_time', '>=', $time_start)
            ->where('create_time', '<=', $time_end)
            ->where('order_status', '>=', 2)
            ->where('goods_type', '=', 0)
            ->where('pay_date', '>=', 0)
            ->where('out_type', '=', 0)
            ->sum('order_total');
        if (empty($order_total)) {
            return 0;
        }
        return $order_total;
    }

    public static function getDayProfit($day)
    {
        $profit = 0;
        $data = self::where('create_date_day', $day)->where('order_status', '>=', 2)->select();
        foreach ($data as $v) {
            $profit_temp = $v['actual_price'] - $v['freight_price'] - $v['cost_price'];
            $profit += $profit_temp;
        }
        return round($profit, 2);
    }

    /**
     * 获取收货号码
     * @param $order_id
     * @return mixed|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getTakePhone($order_id)
    {
        $order_data = self::where(['id' => $order_id])->field('take_phone')->find();
        if (empty($order_data)) {
            return "";
        }
        return $order_data['take_phone'];
    }

    /**
     * 自动任务-获取未付款待取消订单
     */
    public static function getCancelOrder()
    {
        $hour_1 = time() - 3600;
        $map = [
            'order_status' => 1
        ];
        $order_list = self::where($map)->where('create_time', '<=', $hour_1)->select();
        if (empty($order_list)) {
            return [];
        }
        return $order_list;
    }

    /**
     * 获取代理商指定时间区间的利润
     * @param $agency_id
     * @param int $start_time
     * @param int $end_time
     * @param int $agency_settle
     * @return float|int
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getAgencyEarnings($agency_id, $start_time = 0, $end_time = 0, $agency_settle = 0)
    {
        if (empty($start_time) || empty($end_time)) {
            return 0;
        }
        $map = [
            'agency_id' => $agency_id,
            'out_type' => 0
        ];
        if (intval($agency_settle) < 2) {
            $map['agency_settle'] = $agency_settle;
        }
        $order_list = self::where($map)
            ->where('order_status', '>=', 3)
            ->whereBetween('pay_date', $start_time . ',' . $end_time)->field('freight_price,actual_price,cost_price,agency_ratio')
            ->select();
        if (empty($order_list)) {
            return 0;
        }
        $all_profit = 0;
        foreach ($order_list as $value) {
            $profit = floatval($value['actual_price']) - floatval($value['freight_price']) - floatval($value['cost_price']);
            if ($profit > 0) {
                $all_profit += $profit * floatval($value['agency_ratio']);
            }
        }
        return round($all_profit, 2);
    }

    /**
     * 结算指定区间的订单
     * @param $agency_id
     * @param int $start_time
     * @param int $end_time
     * @return bool|int
     */
    public static function settleAgencyOrder($agency_id, $start_time = 0, $end_time = 0)
    {
        if (empty($start_time) || empty($end_time)) {
            return 0;
        }
        $up_data = [
            'agency_settle' => 1
        ];
        $ret = self::where(['agency_id' => $agency_id, 'out_type' => 0, 'agency_settle' => 0])
            ->where('order_status', '>=', 3)
            ->whereBetween('pay_date', $start_time . ',' . $end_time)->update($up_data);
        if ($ret === false) {
            return false;
        }
        return true;
    }

    /**
     * 订单列表
     * @param $user_id
     * @param int $goods_type
     * @return int
     */
    public static function getOrderCount($user_id, $goods_type = 0)
    {
        $map = [
            'user_id' => $user_id,
            'goods_type' => $goods_type,
            'order_status' => 3
        ];
        return self::where($map)->count('id');
    }
}
